package com.example.config.aop;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.modules.entity.PostPopular;
import com.example.service.PostPopularService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

@Aspect
@Component
public class PostCountAspect {
    @Autowired
    public PostPopularService postPopularService;
    @Pointcut(value = "@annotation(com.example.config.aop.PostCount)")
    public void aopAspect(){}
    private ThreadLocal<JSONObject> threadLocal = ThreadLocal.withInitial(JSONObject::new);

    @Before("aopAspect()")
    public void doBefore(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取方法
        Method method = signature.getMethod();
        // 获取方法上面的注解
        PostCount annotation = method.getAnnotation(PostCount.class);
        if (Objects.nonNull(annotation)){
            JSONObject data = new JSONObject();
            Object[] args = joinPoint.getArgs();
            data .put("postId",args[0]);
            threadLocal.set(data);
        }
    }

    @AfterReturning(value = "aopAspect()",returning = "res")
    public void doAfter(Object res){
        JSONObject object = threadLocal.get();
        //防止内存泄漏
        threadLocal.remove();
        if (Objects.nonNull(object)){
            Integer postId = object.getInteger("postId");
            QueryWrapper<PostPopular> qe = new QueryWrapper<>();
            qe.eq("post_id",postId);
            PostPopular postPopular = postPopularService.getOne(qe);
            if (Objects.nonNull(postPopular)){
                postPopular.setHotNum(postPopular.getHotNum() + 1);
                postPopularService.updateById(postPopular);
            }else {
                PostPopular inserPostPopular = new PostPopular();
                inserPostPopular.setPostId(postId);
                inserPostPopular.setHotNum(1);
                postPopularService.getBaseMapper().insert(inserPostPopular);
            }

            //优化这里可以使用redis缓存

        }
    }
}
